import cv2
import numpy as np
import time

output_width=180
output_height=60

def get_char(luminance):
    chars = "@#%!+=_&*$?:"
    return chars[int((luminance/255.0)*(len(chars)-1))]

def video_to_ascii(video_path,output_width,output_height):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise IOError("Error opening video file")
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    print(f"FPS:{fps},Frame Count:{frame_count}")
    print(f"Output height:{output_height}")
    return cap

if __name__ == "__main__":
    
    video_path = "ss.mp4"
    cap = video_to_ascii(video_path,output_width,output_height)
    while True:
        ret,frame = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        resized = cv2.resize(gray,(output_width,output_height),interpolation=cv2.INTER_LINEAR)

        ascii_frame = ""
        for row in resized:
            for luminance in row:
                ascii_frame += get_char(luminance)
            ascii_frame += "\n"
        print(ascii_frame)
        time.sleep(0.1/cap.get(cv2.CAP_PROP_FPS))
    cap.release()
